#!/usr/bin/bash
pro_base="$(cd `dirname $(readlink -f $0)`;pwd)"        # program base directory. readlink是为了获取脚本的真实路径
pro_root="${pro_base##*/}"                              # 我的程序的根目录名字.   readlink使得ln创建的软链也能正确地执行
#pro_name="$(readlink -f $0 | sed 's#^.*/##; s#.sh$##')" # 删除'/'前的路径,删除'.sh'

source ${pro_base}/shared/include.sh || exit 1
Include ${pro_base}/shared/prompt.sh

read -p'需要与 "阿里云的时间服务器" 每个小时进行一次时间同步吗？若租用阿里云的服务器，可选n (y/n 默认:n) ' a                 # answer
case $a in
    y|Y|yes|YES)
        ali_time_cron=1
        ;;
    *)
        ali_time_cron=0             # 0表示:不在crontab配置与阿里云时间服务器进行同步
        ;;
esac

read -p'需要停止firewalld服务以及删除所有防火墙规则吗？ (y/n 默认:n) ' a                 # answer
case $a in
    y|Y|yes|YES)
        clean_firewalld=1
        ;;
    *)
        clean_firewalld=0
        ;;
esac

Eval_cont "cat /etc/rc.d/rc.local"
read -p'要不要用预定义的内容覆盖 /etc/rc.d/rc.local 文件的内容？新的操作系统建议选y (y/n 默认:n) ' a                 # answer
case $a in
    y|Y|yes|YES)
        change_rc_local=1
        ;;
    *)
        change_rc_local=0             # 0表示:不修改/etc/rc.d/rc.local文件的内容
        ;;
esac

Eval_cont "cat /etc/selinux/config"
read -p'selinux的值修改为permissive还是disabled? (p/d 默认:p) ' a                 # answer
case $a in
    p|P)
        change_selinux=permissive
        ;;
	d|D)
		change_selinux=disabled
		;;
    *)
        change_selinux=e
        ;;
esac

read -p'要不要挂载DVD光盘，配置本地YUM源？若是VMware等虚拟机安装的系统，可选y (y/n 默认:n) ' a                 # answer
case $a in
    y|Y|yes|YES)
        local_yum=1
        ;;
    *)
        local_yum=0             # 0表示:不用DVD光盘部署本地YUM源
        ;;
esac

read -p'要不要强制使用非图形界面（文本界面）？作为服务端的操作系统，一般都选y (y/n 默认:n) ' a                 # answer
case $a in
    y|Y|yes|YES)
        graphical_target=0
        ;;
    *)
        graphical_target=1             # 1表示:不要设置默认的target为graphical.target,即默认使用文本multi-user.target
        ;;
esac

if [[ ${local_yum} != 0 ]]; then
    Eval_cont 'mkdir -p /dvd ; mount /dev/sr0 /dvd ; [[ $(df |grep -c dvd) == 0 ]] && exit 1'
    sed -i '/^\/dev\/sr0/d' /etc/fstab
    echo '/dev/sr0 /dvd iso9660 defaults 0 0' >> /etc/fstab; mount -a;
    # 配置本地yum，安装cifs-utils挂载Windows共享文件夹
    cd /etc/yum.repos.d && i="$(ls)" && mkdir bak && mv $i bak
    echo -e '[localYum]\nname=localYum\nbaseurl=file:///dvd\ngpgcheck=0\nenabled=1' > /etc/yum.repos.d/localYum.repo
fi

# 配置 crontab 任务
[[ ! -f /var/spool/cron/root ]] && touch /var/spool/cron/root && chmod 600 /var/spool/cron/root    # 有些系统中没有 /var/spool/cron/root 文件
if [[ ${ali_time_cron} != 0 ]]; then
    [[ $(grep -ac 'ntpdate' /var/spool/cron/root) == 0 ]] &&
    echo '8 * * * * /usr/sbin/ntpdate ntp2.aliyun.com &>> /tmp/crontab_ntpdate.log' >> /var/spool/cron/root
else
    PNote "变量\${ali_time_cron}的值为0,不在crontab配置与阿里云时间服务器进行同步"
fi

if [[ ${clean_firewalld} != 0 ]]; then
    Eval_cont "bash ${pro_base}/firewall.sh clean"   
fi

Eval_cont "mkdir -p /var/log/${pro_root}"
[[ `grep -ac "/var/log/${pro_root}" /var/spool/cron/root` == 0 ]] && echo "11 1 * * * find /var/log/${pro_root} -type f -mtime +32 -delete" >> /var/spool/cron/root
Eval_cont 'crontab -l'
if systemctl status crond.service &> /dev/null; then
    POk "crond服务状态正常."
else
    PWarn "crond服务状态异常,正尝试重启服务" && systemctl restart crond.service ||
    PWarn "crond服务状态仍然异常,请检查" 
fi

if [[ ${change_rc_local} != 0 ]]; then
    # cat命令: '-'表示忽略行首的<tab>,不会忽略行首的<space>,也不忽略行中间的<space>或<tab>; 'EOF'带了引号表示不扩展INPUT中的$a等变量
    cat <<-'EOF' > /etc/rc.d/rc.local
#!/bin/bash
[[ -d /var/log/boot ]] || mkdir -p /var/log/boot
(
fnEvalCont(){
    echo -e "[ \033[1;33mINFO\033[0m ] `date '+%FT%T'` Running: \033[36m$@\033[0m"
    eval "$@"
}
echo -e "\033[1;36m`date '+%FT%T'`: start to run /etc/rc.local\033[0m"
#fnEvalCont "echo 'nameserver 223.5.5.5' >> /etc/resolv.conf"
#fnEvalCont /usr/sbin/ntpdate ntp1.aliyun.com

# # # # # # # # # # # # # # # # # # # # #
#fnEvalCont "bash ${pro_base}/firewall.sh clean"
# 这中间可以执行任何其他代码或脚本
# 注意:通过rc.local在开机时启动的程序,关机时要先关闭这些程序,否则关机时可能会一直卡在"a stop job is running for /etc/rc.d/rc.local"
# 解决方法:sed -i 's/^TimeoutSec=.*/TimeoutSec=9/' /usr/lib/systemd/system/rc-local.service && systemctl daemon-reload
# # # # # # # # # # # # # # # # # # # # #

echo -e "\033[1;36m`date '+%FT%T'`: finish to run /etc/rc.local\033[0m\n"
) &>> /var/log/boot/`date +%F`.log  # less -iR /var/log/boot/`date +%F`.log
EOF
    sed -i "s%\${pro_base}%${pro_base}%" /etc/rc.d/rc.local # ${pro_base}的值带'/',因此s的分隔符不能用'/'
    chmod +x /etc/rc.d/rc.local; ln -sf /etc/rc.d/rc.local /etc/rc.local
    Eval_cont "ls -l --color=auto /etc/rc.local /etc/rc.d/rc.local"      # 部署一下
else
    PNote "变量\${change_rc_local}的值为0,不修改/etc/rc.d/rc.local的内容"
fi

sed -i 's/^TimeoutSec=.*/TimeoutSec=9/' /usr/lib/systemd/system/rc-local.service && systemctl daemon-reload
Eval_cont 'grep TimeoutSec /usr/lib/systemd/system/rc-local.service'
sed -i '/^DefaultTimeout/d' /etc/systemd/system.conf && echo -e 'DefaultTimeoutStartSec=9s\nDefaultTimeoutStopSec=9s' >> /etc/systemd/system.conf
Eval_cont 'grep DefaultTimeout /etc/systemd/system.conf'
# 优化内核参数
Eval_cont bash ${pro_base}/initial_module/kernel.sh

sed -i '/^\*.*soft.*core/d; /^\*.*hard.*core/d' /etc/security/limits.conf
#echo -e '* soft core 1048576\n* hard core 1048576' >> /etc/security/limits.conf                # 会产生很多 core.pid 文件...
# /etc/security/limits.conf文件说core的单位是KB,则1048576KB为1GB,详见/proc/[pid]/limits
#echo -e "mysql soft core unlimited\nmysql hard core unlimited" >> /etc/security/limits.conf        # MariaDB官网的优化建议
sed -i '/^\*.*soft.*nofile/d; /^\*.*hard.*nofile/d' /etc/security/limits.conf
echo -e '* soft nofile 65535\n* hard nofile 65535' >> /etc/security/limits.conf
Eval_cont "tail /etc/security/limits.conf"

# 使用适合自己的 bash 配置
sed -i '/^myVar=/d' /etc/environment; echo 'myVar="${myVar}:/etc/environment"' >> /etc/environment
echo 'myVar="${myVar}:/etc/profile.d/root.sh"' > /etc/profile.d/root.sh
sed -i '/^myVar=/d' /etc/profile; echo 'myVar="${myVar}:/etc/profile"' >> /etc/profile
sed -i '/^myVar=/d' /etc/bashrc; echo 'myVar="${myVar}:/etc/bashrc"' >> /etc/bashrc
sed -i '/^myVar=/d' ${HOME}/.bashrc; echo 'myVar="${myVar}:${HOME}/.bashrc"' >> ${HOME}/.bashrc
sed -i '/^myVar=/d' ${HOME}/.bash_profile; echo 'myVar="${myVar}:${HOME}/.bash_profile"' >> ${HOME}/.bash_profile
sed -i '/^set editing-mode vi/d' /etc/inputrc; echo 'set editing-mode vi' >>/etc/inputrc
sed -i -r '/^PROMPT_COMMAND|^PS1=|^yumDir=|^scrDir=|HISTTIMEFORMAT|HISTCONTROL/d' /etc/bashrc                 # scrDir: directory of my script
PS="PS1='\[\033[32m\][\u\[\033[33m\]@\[\033[32m\]\h \[\033[33m\]\w]# \[\033[0m\]'"
echo "${PS}
yumDir='/etc/yum.repos.d'
scrDir='/opt/${pro_root}'
HISTTIMEFORMAT=\"%FT%T \"
HISTSIZE=999
#HISTFILE=\"/tmp/\`whoami\`.history\"
#PROMPT_COMMAND=\"${PROMPT_COMMAND}; history -a\"   # 实时写入历史命令到\$HISTFILE
unset HISTCONTROL HISTFILESIZE" >>/etc/bashrc
Eval_cont 'tail /etc/bashrc'

# 修改yum.conf
Eval_cont bash ${pro_base}/initial_module/yum.conf.setting.sh

# 关闭防火墙
Eval_cont 'systemctl stop firewalld; systemctl disable firewalld; systemctl status firewalld'
Eval_cont 'systemctl stop iptables ; systemctl disable iptables ; systemctl status iptables'

# 安装iftop(可用阿里云的epel库)
Ali_epel(){
    ! [[ -f /etc/yum.repos.d/CentOS7-Ali-epel.repo ]] &&
echo '[Ali-epel]
name=CentOS7-Ali-epel
baseurl=http://mirrors.aliyun.com/epel/7/$basearch
failovermethod=priority
enabled=1
gpgcheck=0' > /etc/yum.repos.d/CentOS7-Ali-epel.repo
}
Eval_cont Ali_epel
Eval_cont 'type iftop || yum install -y iftop'
Eval_cont 'type vnstat || yum install -y vnstat'
Eval_cont 'systemctl enable vnstat && systemctl restart vnstat'

# 关闭SELinux
[[ -f /etc/selinux/config && "${change_selinux}" != "e" ]] && sed -i "s/^SELINUX=.*$/SELINUX=${change_selinux}/" /etc/selinux/config &&
Eval_cont 'cat /etc/selinux/config; setenforce 0; getenforce'

# 配置logrotate.conf
[[ $(grep -c 'dateyesterday' /etc/logrotate.conf) == 0 ]] && sed -i '/^dateext/a dateyesterday' /etc/logrotate.conf
Eval_cont 'grep --color=auto date /etc/logrotate.conf'

# 安装常用软件
Eval_cont 'yum install -y net-tools psmisc lsof telnet bind-utils sysstat fontconfig mailx expect at'   # 有些软件依赖Ali-updates库?
                        # netstat, pstree,lsof,telnet,nslookup,  sar, 字体配置工具, mail,expect,at
Eval_cont 'systemctl enable atd && systemctl restart atd && systemctl status atd'
# yum install -y deltarpm  #解决Yum安装时出现Delta RPMs disabled because /usr/bin/applydeltarpm not installed的提示

# perl-MIME-Lite 在epel库中
Eval_cont "yum install -y perl-MIME-Lite perl-Net-SMTP-SSL perl-Net-SSLeay perl-Authen-SASL openssl-perl openssl-devel perl-IO-Socket-SSL" ||
    PWarn "send_mail.pl的一些依赖组件安装失败"
Eval_exit "chmod +x ${pro_base}/shared/send_mail.pl && ln -sf ${pro_base}/shared/send_mail.pl /usr/bin"

# yum clean all && yum repolist all # && yum makecache
Eval_cont 'yum install -y vim wget mlocate bash-completion ntp dstat rsync'
Eval_cont bash ${pro_base}/initial_module/vim_deploy.sh
 


# 修改语言,需重启
Eval_cont '(($(localectl |grep -c "en_US.UTF-8"))) || localectl set-locale LANG=en_US.UTF-8 && localectl'
timedatectl set-timezone "Asia/Shanghai"
timedatectl set-local-rtc 0
[[ ${graphical_target} == 0 ]] && [[ "`systemctl get-default`" != "multi-user.target" ]] && systemctl set-default multi-user.target && sync && init 6     # 强制使用非图形界面
# 图形界面是 systemctl set-default graphical.target

if false; then          # 云主机不部署本地仓库
    Eval_cont 'yum list installed cifs-utils || yum install -y cifs-utils'
fi

if false; then          # 先不挂载CIFS啦
    echo '[Unit]
    Description=execute bash script to mount cifs
    # the following line is copied from httpd.service
    After=network.target remote-fs.target nss-lookup.target

    [Service]
    RemainAfterExit=yes
    ExecStartPre=/usr/bin/test -f /opt/HQC/service/mount_cifs.sh
    ExecStart=/usr/bin/bash /opt/HQC/service/mount_cifs.sh
    ExecStop=/usr/bin/umount /dvd /win
    # ExecStop=/usr/bin/umount /d /fuda

    [Install]
    WantedBy=multi-user.target' > /usr/lib/systemd/system/mount_cifs.sh

    Eval_cont 'systemctl enable mount_cifs.service && systemctl restart mount_cifs.service'
    Eval_cont 'df -Th'
fi

swap_size="$(free -h|tail -1|awk '{print $2}')"
if [[ "${swap_size}" == "0B" ]]; then
    PNote "没有SWAP分区"
    read -p'你要新增SWAP分区吗？(y/n 默认:n) ' a
        case $a in
        y|Y|yes|YES)
            read -p'你要创建多少GB的SWAP分区？(1-4 默认:0) ' a
            if [[ $a == 1 || $a == 2 || $a == 3 || $a == 4 ]]; then
                MkSwap(){
                    mkdir /swap && cd /swap/ && dd if=/dev/zero of=swapfile bs=256M count=$((a*4)) && mkswap swapfile
                    echo '/swap/swapfile swap swap defaults 0 0' >> /etc/fstab  && cat /etc/fstab
                    chmod 0600 swapfile && swapon swapfile  && free -h && cat /proc/swaps
                }
                MkSwap
            else
                PWarn "你输入了无效的数字，不创建SWAP分区"
            fi
            ;;
        *)
            :                   # 不创建分区，什么也不做
            ;;
    esac
else
    POk "SWAP分区的大小为: ${swap_size}"
fi

if false; then
    没有swap分区的，按如下制作swap分区
    [root@iZwz910titmx3dtnicmsnaZ ~]# free -h
                  total        used        free      shared  buff/cache   available
    Mem:           3.7G        1.4G        537M        484K        1.8G        2.0G     # 内存为4G，故swap分区也分4G
    Swap:            0B          0B          0B

    mkdir /swap && cd /swap/
    dd if=/dev/zero of=swapfile bs=256M count=4                                         # 如果内存只有1G则无法创建bs=1G的块
    # 4+0 records in
    # 4+0 records out
    # 4294967296 bytes (4.3 GB) copied, 55.9664 s, 76.7 MB/s
    [root@iZwz910titmx3dtnicmsnaZ swap]# mkswap swapfile                                # 格式化swap文件
    Setting up swapspace version 1, size = 4194300 KiB
    no label, UUID=e16d94e5-4a0c-4464-ab00-257e85014bf6

    echo '/swap/swapfile swap swap defaults 0 0' >> /etc/fstab  && cat /etc/fstab       # 开机挂载swap
    chmod 0600 swapfile && swapon swapfile  && free -h && cat /proc/swaps               # 启用swap文件

    取消swap分区
    [root@centos1611 /root]# swapoff /swap/swapfile
    [root@centos1611 /root]# sed -i '/swapfile/d' /etc/fstab
    [root@centos1611 /root]# rm -rf /swap/
fi

# 下面是过期无用的代码
# 常德云计算中心
if false; then
    (( `grep -c DNS1 /etc/sysconfig/network-scripts/ifcfg-ens160` < 1 )) && echo DNS1=223.5.5.5 >> /etc/sysconfig/network-scripts/ifcfg-ens160  # 添加DNS
    (( `grep -c DNS2 /etc/sysconfig/network-scripts/ifcfg-ens160` < 1 )) && echo DNS2=114.114.114.114 >> /etc/sysconfig/network-scripts/ifcfg-ens160
    systemctl restart network NetworkManager
fi
